package com.tom.architect.party3.day25.okhttp;

import android.util.Log;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

/**
 *
 */
public class RealCall implements Call {
    private final Request originalRequest; // 原始请求
    private final OkHttpClient client;

    public RealCall(Request request, OkHttpClient client) {
        this.originalRequest = request;
        this.client = client;
    }

    public static Call newCall(Request request, OkHttpClient okHttpClient) {
        return new RealCall(request, okHttpClient);
    }
    @Override
    public void enqueue(Callback callback) {
        // 异步请求
        AsyncCall asyncCall = new AsyncCall(callback);
        // 交给线程池。
        client.dispatcher.enqueue(asyncCall);
    }

    @Override
    public Response execute() {
        return null;
    }

    // 内部类。
    final class AsyncCall extends NamedRunnable {
        private Callback callback;

        public AsyncCall(Callback callback) {
            this.callback = callback;
        }

        @Override
        protected void execute() { // NamedRunnable 的 run() 方法
            // 真正开始访问网络，将request --> response。
            Log.e("TAG", "execute: 232323");
            // Volley，xUtils，Afinal，AsyHttpClient
            // Demo 暂时基于HttpUrlConnection; okHttp = Socket+ okio(IO输入输出流)

            final Request request = originalRequest;
            try {
                URL url = new URL(request.url);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                if (urlConnection instanceof HttpsURLConnection) {
                    HttpsURLConnection httpsURLConnection = (HttpsURLConnection) urlConnection;
                    // https 设置证书
//                    httpsURLConnection.setHostnameVerifier();
//                    httpsURLConnection.setSSLSocketFactory();
                }
                urlConnection.setReadTimeout(30);

                // POST 写东西
                urlConnection.setRequestMethod(request.method.name);
                urlConnection.setDoInput(request.method.doOutput()); // A URL connection can be used for input and/or output.
                urlConnection.connect(); // HttpURLConnection 连接
                //  写，判断requestBody是否有。
                RequestBody requestBody = request.requestBody;
                if (requestBody != null) {
                    // 头信息:type 长度
                    urlConnection.setRequestProperty("Context-Type", requestBody.getContentType());
                    urlConnection.setRequestProperty("Context-Length", Long.toString(requestBody.getContentLength()));
                }
                // 写内容体。将output写入到writeBody中
                if (requestBody != null) {
                    requestBody.onWriteBody(urlConnection.getOutputStream());
                }

                int statusCode = urlConnection.getResponseCode(); // 进行操作，获取状态码，
                if (200 == statusCode) {
                    InputStream inputStream = urlConnection.getInputStream();
                    // inputStream 转成byte，给到Response里面。
                    Response response = new Response(inputStream);
                    callback.onResponse(RealCall.this, response);
                }

            } catch (IOException e) {
                e.printStackTrace();
                callback.onFailure(RealCall.this, e);
            }
        }
    }

}
